<?php
declare(strict_types=1);
/**
 * MineAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using MineAdmin.
 *
 * @Author X.Mo<root@imoi.cn>
 * @Link   https://gitee.com/xmo/MineAdmin
 */

namespace App\User\Mapper;

use App\User\Model\UserInfo;
use Hyperf\Database\Model\Builder;
use Mine\Abstracts\AbstractMapper;
use Mine\MineModel;

/**
 * 用户信息表Mapper类
 */
class UserInfoMapper extends AbstractMapper
{
    /**
     * @var UserInfo
     */
    public $model;

    public function assignModel()
    {
        $this->model = UserInfo::class;
    }

    /**
     * 搜索处理器
     * @param Builder $query
     * @param array $params
     * @return Builder
     */
    public function handleSearch(Builder $query, array $params): Builder
    {

        // ID
        if (isset($params['id']) && filled($params['id'])) {
            $query->where('id', '=', $params['id']);
        }

        // 用户vip_id,随机，不可重复
        if (isset($params['room_no']) && filled($params['room_no'])) {
            $query->where('room_no', '=', $params['room_no']);
        }

        // 父节点
        if (isset($params['pid']) && filled($params['pid'])) {
            $query->where('pid', '=', $params['pid']);
        }

        // 昵称
        if (isset($params['nickname']) && filled($params['nickname'])) {
            $query->where('nickname', 'like', '%' . $params['nickname'] . '%');
        }

        // 头像
        if (isset($params['avatar']) && filled($params['avatar'])) {
            $query->where('avatar', 'like', '%' . $params['avatar'] . '%');
        }

        // 手机号
        if (isset($params['mobile']) && filled($params['mobile'])) {
            $query->where('mobile', 'like', '%' . $params['mobile'] . '%');
        }

        // 邮箱
        if (isset($params['email']) && filled($params['email'])) {
            $query->where('email', 'like', '%' . $params['email'] . '%');
        }

        // 性别0:未知,1男,2:女
        if (isset($params['gender']) && filled($params['gender'])) {
            $query->where('gender', '=', $params['gender']);
        }

        // 交易联接
        if (isset($params['trade_url']) && filled($params['trade_url'])) {
            $query->where('trade_url', 'like', '%' . $params['trade_url'] . '%');
        }

        // 标识符,1-散户,2-内部用户
        if (isset($params['is_flag']) && filled($params['is_flag'])) {
            $query->where('is_flag', '=', $params['is_flag']);
        }

        // 是否已实名1实名，2 未实名
        if (isset($params['is_real_name']) && filled($params['is_real_name'])) {
            $query->where('is_real_name', '=', $params['is_real_name']);
        }

        // 最后登陆ip
        if (isset($params['login_last_ip']) && filled($params['login_last_ip'])) {
            $query->where('login_last_ip', 'like', '%' . $params['login_last_ip'] . '%');
        }

        // 最后登陆时间
        if (isset($params['login_last_time']) && filled($params['login_last_time']) && is_array($params['login_last_time']) && count($params['login_last_time']) == 2) {
            $query->whereBetween(
                'login_last_time',
                [$params['login_last_time'][0], $params['login_last_time'][1]]
            );
        }

        // 邀请码
        if (isset($params['invite_code']) && filled($params['invite_code'])) {
            $query->where('invite_code', 'like', '%' . $params['invite_code'] . '%');
        }

        // 来源类型
        if (isset($params['source_type']) && filled($params['source_type'])) {
            $query->where('source_type', '=', $params['source_type']);
        }

        // 用户状态 1正常 2冻结 3:注销
        if (isset($params['status']) && filled($params['status'])) {
            $query->where('status', '=', $params['status']);
        }

        // 备注或是签名(测试账号可能会做个备注)
        if (isset($params['remark']) && filled($params['remark'])) {
            $query->where('remark', 'like', '%' . $params['remark'] . '%');
        }

        // 创建者
        if (isset($params['created_by']) && filled($params['created_by'])) {
            $query->where('created_by', '=', $params['created_by']);
        }

        // 创建时间
        if (isset($params['create_time']) && filled($params['create_time'])) {
            $query->whereBetween(
                'create_time',
                [$params['create_time'][0], $params['create_time'][1]]
            );
        }

        // 更新时间
        if (isset($params['update_time']) && filled($params['update_time'])) {
            $query->where('update_time', '=', $params['update_time']);
        }

        // 删除数据
        if (isset($params['delete_time']) && filled($params['delete_time'])) {
            $query->where('delete_time', '=', $params['delete_time']);
        }

        return $query;
    }

    public function save(array $data): mixed
    {
        $data['room_no'] = \Ziyancs\Zytool\Extends\ToolFun::makeOnlyId($this->userInfoModel::REDIS_MAKE_ROOM_NO);//生成编号
        $type = $this->userSocialModel::TYPE_USERNAME; //生成登陆类型
        $data['invite_code'] = \Ziyancs\Zytool\Extends\ToolFun::makeOnlyId($this->userInfoModel::REDIS_MAKE_INVITE_NO, 2, 6); //生成邀请码
        $this->filterExecuteAttributes($data, $this->getModel()->incrementing);
        $model = $this->model::create($data);
        return $model->{$model->getKeyName()};
    }

    public function update(mixed $id, array $data): bool
    {
        $this->filterExecuteAttributes($data, true);
        return $this->model::find($id)->update($data) > 0;
    }

    /**
     * 用户列表
     * @param array|null $params
     * @param bool $isScope
     * @param string $pageName
     * @return array
     */
    public function getPageList(?array $params, bool $isScope = true, string $pageName = 'page'): array
    {
        $paginate = $this->listQuerySetting($params, $isScope)->paginate(
            (int)($params['pageSize'] ?? $this->model::PAGE_SIZE),
            ['*'],
            $pageName,
            (int)($params[$pageName] ?? 1)
        );
        $parentUserIds = [];
        foreach ($paginate->items() as $item) {
            if (!empty($item->pid)) {
                $parentUserIds[] = $item->pid;
            }
        }
        $parentUserArrDb = $this->model::query()->whereIn('id', $parentUserIds)->pluck('mobile', 'id');
        $parentUserArr = $parentUserArrDb->isEmpty() ? [] : $parentUserArrDb->toArray();
        foreach ($paginate->items() as &$item) {
            if (!empty($item->pid)) {
                $item->parent_name = $parentUserArr[$item->pid];
            } else {
                $item->parent_name = '';
            }
        }
        return $this->setPaginate($paginate, $params);
    }

    /**
     * 单条用户信息
     * @param mixed $id
     * @param array $column
     * @return MineModel|null
     */
    public function read(mixed $id, array $column = ['*']): ?MineModel
    {
        $res = ($model = $this->model::with(['account'])->find($id, $column)) ? $model : null;
        //获取背包总值--未提出总值
        $sumBagPrice = \App\User\Model\UserBag::query()
            ->where('user_id', $id)
            ->whereIn('status', [1, 3])
            ->sum('price');
        if (!empty($res)) {
            //背包总金额
            $res->bag_sum_price = $sumBagPrice;
            //推广人
            if (!empty($res->pid)) {
                $parentUserArrDb = $this->model::query()->select(['id', 'nickname', 'mobile', 'is_flag'])->where('id', $res->pid)->first();
                $res->parent_mobile = $parentUserArrDb->mobile;
                $res->parent_is_flag = $parentUserArrDb->is_flag;
            } else {
                $res->parent_mobile = '';
                $res->parent_is_flag = '';
            }
            //是否黑名单
            $res->back_is_exits = \App\Record\Model\RecordMobileBack::query()->where('mobile', $res->mobile)->exists();
            //获取部门
            $user = \App\System\Model\SystemUser::withTrashed()->find($res->created_by);
            if ($user) {
                $user->setAttribute('deptList', $user->depts()->get(['id', 'name']) ?: []);
            }
            $deptArr = [];
            foreach ($user->deptList as $dept) {
                $deptArr[] = $dept->name;
            }
            $res->dept_list = implode(',', $deptArr);

        }
        return $res;
    }

    /**
     * 更新上级
     * @param mixed $id
     * @param array $data
     * @return bool
     */

    public function updateParent(mixed $id, array $data): bool
    {
        $this->filterExecuteAttributes($data, true);
        return $this->model::find($id)->update($data) > 0;
    }

    /**
     * 重设密码
     * @param mixed $id
     * @param array $data
     * @return bool
     */

    public function resetPassword(mixed $id, array $data): bool
    {
        $this->filterExecuteAttributes($data, true);
        return $this->model::find($id)->update($data) > 0;
    }

    /**
     * 清除登录ip
     * @param mixed $id
     * @param array $data
     * @return bool
     */

    public function clearLoginIp(mixed $id, array $data): bool
    {
        $this->filterExecuteAttributes($data, true);
        return $this->model::find($id)->update($data) > 0;
    }

}